package cn.hznc.controller.service.toolAnalyze;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.controller.service.toollife.ToolLieService;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.inventory.SingleWarehouseSafetyInventoryParam;
import cn.hznc.domain.request.toolAnalyze.ToolTypeUsageAnalysisReportDetailReq;
import cn.hznc.domain.request.toolAnalyze.ToolTypeUsageAnalysisReportReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.mapper.*;
import cn.hznc.repository.*;
import cn.hznc.utils.CommonUtil;
import cn.hznc.vo.InOrOutboundRecordVo;
import cn.hznc.vo.InOrOutboundSumVo;
import cn.hznc.vo.LocationNameVo;
import cn.hznc.vo.ToolStockVo;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ToolTypeUsageAnalysisReportService {

    @Resource
    private EntryExitRecordMapper entryExitRecordMapper;

    @Resource
    private EntryExitRecordRepository entryExitRecordRepository;
    @Resource
    private ToolPartMapper toolPartMapper;
    @Resource
    private WarehouseMapper warehouseMapper;
    @Resource
    private InventoryLocationRespository inventoryLocationRespository;

    @Resource
    private ToolInventoryLocationRespository toolInventoryLocationRespository;
    @Resource
    private TypeItemMapper typeItemMapper;
    @Resource
    private MinioProp minioProp;
    @Resource
    private ToolPartEntryExitRecordMapper toolPartEntryExitRecordMapper;

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private ToolForkInfoRespository toolForkInfoRespository;

    @Resource
    private ToolPartRespository toolPartRespository;

    @Resource
    private ToolLieService toolLieService;

    @Transactional
    public PageResult<ToolTypeUsageAnalysisReportEntity> queryToolTypeUsageAnalysisReport(ToolTypeUsageAnalysisReportReq toolTypeUsageAnalysisReportReq) {
        List<ToolTypeUsageAnalysisReportEntity> toolTypeUsageAnalysisReportEntities = new ArrayList<>();
        List<Integer> integers = new ArrayList<>();
        LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        if (toolTypeUsageAnalysisReportReq.getType().equals("0")) {
            lambdaQueryWrapper5.ne(ToolPartEntity::getToolNo, "");
        }
        if (toolTypeUsageAnalysisReportReq.getType().equals("1")) {
            lambdaQueryWrapper5.ne(ToolPartEntity::getPartno, "");
        }

        List<ToolPartEntity> toolPartEntityList = toolPartMapper.selectList(lambdaQueryWrapper5);
        Map<String, List<ToolPartEntity>> stringIntegerMap = new HashMap<>();
        if (toolTypeUsageAnalysisReportReq.getType().equals("0")) {
            stringIntegerMap = toolPartEntityList.stream().collect(Collectors.groupingBy(ToolPartEntity::getToolNo));

        }
        if (toolTypeUsageAnalysisReportReq.getType().equals("1")) {
            stringIntegerMap = toolPartEntityList.stream().collect(Collectors.groupingBy(ToolPartEntity::getPartno));

        }

        int flag = 0;
        int startPage = (toolTypeUsageAnalysisReportReq.getPageNo() - 1) * toolTypeUsageAnalysisReportReq.getPageSize();
        int endPage = toolTypeUsageAnalysisReportReq.getPageNo() * toolTypeUsageAnalysisReportReq.getPageSize();
        if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getType()) && toolTypeUsageAnalysisReportReq.getType().equals("1")) {
            LambdaQueryWrapper<EntryExitRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (toolTypeUsageAnalysisReportReq.getStartTime() != null && toolTypeUsageAnalysisReportReq.getEndTime() != null) {
                if (toolTypeUsageAnalysisReportReq.getStartTime().equals(toolTypeUsageAnalysisReportReq.getEndTime())) {
                    Date date = toolTypeUsageAnalysisReportReq.getEndTime();
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(date);
                    calendar.add(Calendar.DATE, 1);
                    date = calendar.getTime();
                    toolTypeUsageAnalysisReportReq.setEndTime(date);
                }
                lambdaQueryWrapper.between(EntryExitRecordEntity::getCreateTime, toolTypeUsageAnalysisReportReq.getStartTime(), toolTypeUsageAnalysisReportReq.getEndTime());
            } else {
                lambdaQueryWrapper.between(EntryExitRecordEntity::getCreateTime, LocalDate.now().minusMonths(1), LocalDate.now());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getPartno())) {
                lambdaQueryWrapper.like(EntryExitRecordEntity::getPartno, toolTypeUsageAnalysisReportReq.getPartno());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getToolNo())) {
                lambdaQueryWrapper.like(EntryExitRecordEntity::getToolNo, toolTypeUsageAnalysisReportReq.getToolNo());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getWarehouseType())) {
                lambdaQueryWrapper.eq(EntryExitRecordEntity::getWarehouseType, toolTypeUsageAnalysisReportReq.getWarehouseType());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getInboundAndOutBoundType())) {
                if (toolTypeUsageAnalysisReportReq.getInboundAndOutBoundType().equals("inbound")) {
                    lambdaQueryWrapper.eq(EntryExitRecordEntity::getType, "inbound");
                } else if (toolTypeUsageAnalysisReportReq.getInboundAndOutBoundType().equals("outbound")) {
                    lambdaQueryWrapper.eq(EntryExitRecordEntity::getType, "outbound");
                }
            }
            lambdaQueryWrapper.ne(EntryExitRecordEntity::getPartno, "");
            List<EntryExitRecordEntity> entryExitRecordEntityList1 = entryExitRecordMapper.selectList(lambdaQueryWrapper);
            Map<String, List<EntryExitRecordEntity>> map = entryExitRecordEntityList1.stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getPartno));
            Iterator<Map.Entry<String, List<EntryExitRecordEntity>>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
//                if(toolTypeUsageAnalysisReportEntities.size()>=toolTypeUsageAnalysisReportReq.getPageSize()){
//                    break;
//                }
                Map.Entry<String, List<EntryExitRecordEntity>> entry = entries.next();
                Map<Object, List<EntryExitRecordEntity>> map0 = entry.getValue().stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getWarehouseName())));
                Iterator<Map.Entry<Object, List<EntryExitRecordEntity>>> entries2 = map0.entrySet().iterator();
                integers.add(map0.size());
                if (toolTypeUsageAnalysisReportEntities.size() < toolTypeUsageAnalysisReportReq.getPageSize() || StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {
                    while (entries2.hasNext()) {
                        Map.Entry<Object, List<EntryExitRecordEntity>> entry2 = entries2.next();
                        if (flag < endPage || StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {
                            flag++;
                        } else {
                            break;
                        }
                        if (flag > startPage || StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {

                            ToolTypeUsageAnalysisReportEntity toolTypeUsageAnalysisReportEntity = new ToolTypeUsageAnalysisReportEntity();
                            toolTypeUsageAnalysisReportEntity.setLocation(entry2.getKey());
                            toolTypeUsageAnalysisReportEntity.setType("刀具");
                            toolTypeUsageAnalysisReportEntity.setMaterialNo(entry.getKey());
                            toolTypeUsageAnalysisReportEntity.setCreateTime(entry2.getValue().get(0).getCreateTime());
//                            LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
//                            lambdaQueryWrapper1.eq(ToolPartEntity::getPartno, entry.getKey());
//                            List<ToolPartEntity> toolPartEntityList = toolPartMapper.selectList(lambdaQueryWrapper1);
                            if (stringIntegerMap.containsKey(entry.getKey()))
                                toolTypeUsageAnalysisReportEntity.setLocationNum(stringIntegerMap.get(entry.getKey()).size());
                            if (CollectionUtil.isNotEmpty(stringIntegerMap.get(entry.getKey()))) {
                                String img = minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + stringIntegerMap.get(entry.getKey()).get(0).getImage();
                                toolTypeUsageAnalysisReportEntity.setImg(img);
                            }
                            Map<String, List<EntryExitRecordEntity>> map1 = entry2.getValue().stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getType));
                            try {
                                toolTypeUsageAnalysisReportEntity.setInboundNum(map1.get("inbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber)));
                            } catch (Exception e) {
                            }
                            try {
                                toolTypeUsageAnalysisReportEntity.setOutboundNum(map1.get("outbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber)));
                            } catch (Exception e) {
                            }
                            QueryWrapper<WarehouseEntity> queryWrapper = new QueryWrapper<>();
                            queryWrapper.ne("safety_inventory_configure_param", "");
                            List<Integer> warehouseIdList = new ArrayList<>();
                            entry2.getValue().forEach(s -> {
                                warehouseIdList.add(s.getWarehouseId());
                            });
                            queryWrapper.select("safety_inventory_configure_param").in("id", warehouseIdList);
                            List<WarehouseEntity> warehouseEntities = warehouseMapper.selectList(queryWrapper);
                            warehouseEntities.forEach(warehouseEntity -> {
                                if (StringUtils.isNotEmpty(warehouseEntity.getSafetyInventoryConfigureParam()) && !warehouseEntity.getSafetyInventoryConfigureParam().equals("[]")) {
                                    String s = warehouseEntity.getSafetyInventoryConfigureParam();
                                    Map<String, String> map2 = this.stringToMap(s);
                                    if (map2.get("partno").equals(entry.getKey())) {
                                        toolTypeUsageAnalysisReportEntity.setSafeNum(map2.get("safetyInventory"));
                                    }
                                }
                            });
                            toolTypeUsageAnalysisReportEntities.add(toolTypeUsageAnalysisReportEntity);
                        }
                    }

                }
            }
        }

        if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getType()) && toolTypeUsageAnalysisReportReq.getType().equals("0")) {
            LambdaQueryWrapper<EntryExitRecordEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            if (toolTypeUsageAnalysisReportReq.getStartTime() != null && toolTypeUsageAnalysisReportReq.getEndTime() != null) {
                lambdaQueryWrapper1.between(EntryExitRecordEntity::getCreateTime, toolTypeUsageAnalysisReportReq.getStartTime(), toolTypeUsageAnalysisReportReq.getEndTime());
            } else {
                lambdaQueryWrapper1.between(EntryExitRecordEntity::getCreateTime, LocalDate.now().minusMonths(1), LocalDate.now());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getPartno())) {
                lambdaQueryWrapper1.like(EntryExitRecordEntity::getPartno, toolTypeUsageAnalysisReportReq.getPartno());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getWarehouseType())) {
                lambdaQueryWrapper1.eq(EntryExitRecordEntity::getWarehouseType, toolTypeUsageAnalysisReportReq.getWarehouseType());
            }
            if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getInboundAndOutBoundType())) {
                if (toolTypeUsageAnalysisReportReq.getInboundAndOutBoundType().equals("inbound")) {
                    lambdaQueryWrapper1.eq(EntryExitRecordEntity::getType, "inbound");
                } else if (toolTypeUsageAnalysisReportReq.getInboundAndOutBoundType().equals("outbound")) {
                    lambdaQueryWrapper1.eq(EntryExitRecordEntity::getType, "outbound");
                }
            }
            lambdaQueryWrapper1.ne(EntryExitRecordEntity::getToolNo, "");
            List<EntryExitRecordEntity> entryExitRecordEntityList2 = entryExitRecordMapper.selectList(lambdaQueryWrapper1);
            Map<String, List<EntryExitRecordEntity>> map3 = entryExitRecordEntityList2.stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getToolNo));
            Iterator<Map.Entry<String, List<EntryExitRecordEntity>>> entries1 = map3.entrySet().iterator();
            while (entries1.hasNext()) {
//                if(toolTypeUsageAnalysisReportEntities.size()>=toolTypeUsageAnalysisReportReq.getPageSize()){
//                    break;
//                }
                Map.Entry<String, List<EntryExitRecordEntity>> entry = entries1.next();
                Map<String, List<EntryExitRecordEntity>> map0 = entry.getValue().stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getWarehouseName));
                Iterator<Map.Entry<String, List<EntryExitRecordEntity>>> entries2 = map0.entrySet().iterator();
                integers.add(map0.size());
                if (toolTypeUsageAnalysisReportEntities.size() < toolTypeUsageAnalysisReportReq.getPageSize() || StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {
                    while (entries2.hasNext()) {
                        if (flag < endPage || StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {
                            flag++;
                        } else {
                            break;
                        }
                        if (flag > startPage || StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {
                            Map.Entry<String, List<EntryExitRecordEntity>> entry2 = entries2.next();
                            ToolTypeUsageAnalysisReportEntity toolTypeUsageAnalysisReportEntity1 = new ToolTypeUsageAnalysisReportEntity();
                            toolTypeUsageAnalysisReportEntity1.setCreateTime(entry2.getValue().get(0).getCreateTime());
                            toolTypeUsageAnalysisReportEntity1.setLocation(entry2.getKey());
                            toolTypeUsageAnalysisReportEntity1.setType("总成");
                            toolTypeUsageAnalysisReportEntity1.setToolName(entry.getKey());
//                            LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
//                            lambdaQueryWrapper3.eq(ToolPartEntity::getToolNo, entry.getKey());
//                            List<ToolPartEntity> toolPartEntityList = toolPartMapper.selectList(lambdaQueryWrapper3);
                            if (stringIntegerMap.containsKey(entry.getKey()))
                                toolTypeUsageAnalysisReportEntity1.setLocationNum(stringIntegerMap.get(entry.getKey()).size());
                            if (CollectionUtil.isNotEmpty(toolPartEntityList)) {
                                String img = minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + toolPartEntityList.get(0).getImage();
                                toolTypeUsageAnalysisReportEntity1.setImg(img);
                            }
                            Map<String, List<EntryExitRecordEntity>> map1 = entry2.getValue().stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getType));
                            try {
                                toolTypeUsageAnalysisReportEntity1.setInboundNum(map1.get("inbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber)));
                            } catch (Exception e) {
                            }
                            try {
                                toolTypeUsageAnalysisReportEntity1.setOutboundNum(map1.get("outbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber)));
                            } catch (Exception e) {
                            }
                            QueryWrapper<WarehouseEntity> queryWrapper = new QueryWrapper<>();
//                lambdaQueryWrapper2.ne(WarehouseEntity::getSafetyInventoryConfigureParam, null);
                            queryWrapper.ne("safety_inventory_configure_param", "");
                            List<Integer> warehouseIdList = new ArrayList<>();
                            entry2.getValue().forEach(s -> {
                                warehouseIdList.add(s.getWarehouseId());
                            });
                            queryWrapper.select("safety_inventory_configure_param").in("id", warehouseIdList);
                            List<WarehouseEntity> warehouseEntities = warehouseMapper.selectList(queryWrapper);
                            warehouseEntities.forEach(warehouseEntity -> {
                                if (StringUtils.isNotEmpty(warehouseEntity.getSafetyInventoryConfigureParam()) && !"[]".equals(warehouseEntity.getSafetyInventoryConfigureParam())) {
                                    String s = warehouseEntity.getSafetyInventoryConfigureParam();
                                    Map<String, String> map2 = this.stringToMap(s);
                                    if (map2.get("toolNo").equals(entry.getKey())) {
                                        toolTypeUsageAnalysisReportEntity1.setSafeNum(map2.get("safetyInventory"));
                                    }
                                }

                            });
                            toolTypeUsageAnalysisReportEntities.add(toolTypeUsageAnalysisReportEntity1);
                        }

                    }

                }

            }
        }

        if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportReq.getSafeNumType())) {
            List<ToolTypeUsageAnalysisReportEntity> list = new ArrayList<>();
            toolTypeUsageAnalysisReportEntities.forEach(toolTypeUsageAnalysisReportEntity -> {
                if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportEntity.getSafeNum())) {
                    if (toolTypeUsageAnalysisReportEntity.getLocationNum() < Integer.parseInt(toolTypeUsageAnalysisReportEntity.getSafeNum())) {
                        list.add(toolTypeUsageAnalysisReportEntity);
                    }
                }
            });
            PageInfo<ToolTypeUsageAnalysisReportEntity> result = new PageInfo<>(CommonUtil.pageList(list, toolTypeUsageAnalysisReportReq.getPageNo(), toolTypeUsageAnalysisReportReq.getPageSize()));
            return new PageResult<>(result.getList(), (long) list.size());
        } else {
            PageInfo<ToolTypeUsageAnalysisReportEntity> result = new PageInfo<>(toolTypeUsageAnalysisReportEntities);
            return new PageResult<>(result.getList(), (long) integers.stream().reduce(Integer::sum).orElse(0));
        }

    }


    public PageResult qryLowSafetyInventory(ToolTypeUsageAnalysisReportReq toolTypeUsageAnalysisReportReq) {
        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.selectAllList();
        //List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.selectAllListByWarehouseType(toolTypeUsageAnalysisReportReq.getWarehouseType());
        List<ToolInventoryLocationEntity> filterList = new ArrayList<>();
        List<ToolInventoryLocationEntity> pageList = new ArrayList<>();
        Map<String, List<ToolForkInfoEntity>> groupByPartnoMap = new HashMap<>();
        Map<String, List<ToolInventoryLocationEntity>> groupByPartnoConcatMap = new HashMap<>();
        Map<Integer, List<ToolForkInfoEntity>> groupByIdMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(inventoryLocationEntities)) {
            List<SingleWarehouseSafetyInventoryParam> paramsList = new ArrayList<>();
            for (InventoryLocationEntity inventoryLocationEntity : inventoryLocationEntities) {
                if (StringUtils.isNotEmpty(inventoryLocationEntity.getSafetyInventoryConfigureParam()) && !"[]".equals(inventoryLocationEntity.getSafetyInventoryConfigureParam())) {
                    List<SingleWarehouseSafetyInventoryParam> params = JSONArray.parseArray(inventoryLocationEntity.getSafetyInventoryConfigureParam(), SingleWarehouseSafetyInventoryParam.class);
                    if (CollectionUtil.isNotEmpty(params)) {
                        params.forEach(singleWarehouseSafetyInventoryParam -> singleWarehouseSafetyInventoryParam.setInventoryLocationId(inventoryLocationEntity.getId()));
                        paramsList.addAll(params);
                    }
                }
            }

            List<String> partnos = paramsList.stream()
                    .filter(singleWarehouseSafetyInventoryParam -> StringUtils.isNotBlank(singleWarehouseSafetyInventoryParam.getPartno()))
                    .map(singleWarehouseSafetyInventoryParam -> singleWarehouseSafetyInventoryParam.getPartno().trim())
                    .distinct()
                    .collect(Collectors.toList());
            List<ToolForkInfoEntity> toolForkInfoEntities = toolForkInfoRespository.selectIdByPartnos(partnos);
            if (CollectionUtil.isNotEmpty(toolForkInfoEntities)) {
                groupByPartnoMap = toolForkInfoEntities.stream().collect(Collectors.groupingBy(ToolForkInfoEntity::getPartno));
                groupByIdMap = toolForkInfoEntities.stream().collect(Collectors.groupingBy(ToolForkInfoEntity::getId));
                for (SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam : paramsList) {
                    if (StringUtils.isNotBlank(singleWarehouseSafetyInventoryParam.getPartno())) {
                        singleWarehouseSafetyInventoryParam.setToolId(CollectionUtil.isNotEmpty(groupByPartnoMap.get(singleWarehouseSafetyInventoryParam.getPartno())) ?
                                groupByPartnoMap.get(singleWarehouseSafetyInventoryParam.getPartno()).get(0).getId() : null);
                        if(ObjectUtil.isNotNull(singleWarehouseSafetyInventoryParam.getToolId()) && ObjectUtil.isNotNull(singleWarehouseSafetyInventoryParam.getInventoryLocationId())){
                            singleWarehouseSafetyInventoryParam.setGroupId(singleWarehouseSafetyInventoryParam.getToolId() + ""  + singleWarehouseSafetyInventoryParam.getInventoryLocationId());
                        }
                    }
                }
            }

            List<ToolInventoryLocationEntity> toolInventoryLocationEntities = toolInventoryLocationRespository.selectListByConditions(paramsList.stream()
                    .filter(singleWarehouseSafetyInventoryParam -> StringUtils.isNotBlank(singleWarehouseSafetyInventoryParam.getGroupId()))
                    .map(SingleWarehouseSafetyInventoryParam::getGroupId)
                    .distinct()
                    .collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty(toolInventoryLocationEntities)) {
                groupByPartnoConcatMap = toolInventoryLocationEntities
                        .stream()
                        .collect(Collectors.groupingBy(ToolInventoryLocationEntity::getGroupId));
            }

            for (SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam : paramsList) {
                //ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOneToolReload(inventoryLocationEntity.getId(), singleWarehouseSafetyInventoryParam.getPartno());
                ToolInventoryLocationEntity toolInventoryLocationEntity = CollectionUtil.isNotEmpty(groupByPartnoConcatMap.get(singleWarehouseSafetyInventoryParam.getGroupId()))? groupByPartnoConcatMap.getOrDefault(singleWarehouseSafetyInventoryParam.getGroupId() , new ArrayList<>()).get(0) : null;
                if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
                    if (singleWarehouseSafetyInventoryParam.getSafetyInventory() > toolInventoryLocationEntity.getPhysicalInventory()) {
                        toolInventoryLocationEntity.setSafetyInventory(singleWarehouseSafetyInventoryParam.getSafetyInventory());
                        //ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectById(toolInventoryLocationEntity.getToolId());
                        ToolForkInfoEntity toolForkInfoEntity = CollectionUtil.isNotEmpty(groupByIdMap.get(singleWarehouseSafetyInventoryParam.getToolId()))? groupByIdMap.getOrDefault(singleWarehouseSafetyInventoryParam.getToolId() , new ArrayList<>()).get(0) : new ToolForkInfoEntity();
                        if(ObjectUtil.isNull(toolForkInfoEntity)){
                            continue;
                        }
                        toolInventoryLocationEntity.setPartno(toolForkInfoEntity.getPartno());
                        if (toolForkInfoEntity.getType().startsWith("A001B001")) {
                            toolInventoryLocationEntity.setType("刀具");
                        } else if (toolForkInfoEntity.getType().startsWith("A001B002")) {
                            toolInventoryLocationEntity.setType("工具系统");
                        } else if (toolForkInfoEntity.getType().startsWith("A001B003")) {
                            toolInventoryLocationEntity.setType("刀片");
                        } else if (toolForkInfoEntity.getType().startsWith("A001B004")) {
                            toolInventoryLocationEntity.setType("未分组");
                        }
                        //toolInventoryLocationEntity.setLocationName(toolLieService.getLocationNameByLocationId(inventoryLocationEntity.getId() , ""));
                        filterList.add(toolInventoryLocationEntity);
                    }
                }
            }
        }
        //物料编码过滤
        if (StringUtils.isNotBlank(toolTypeUsageAnalysisReportReq.getPartno())) {
            filterList = filterList.stream().filter(toolInventoryLocationEntity -> toolInventoryLocationEntity.getPartno().contains(toolTypeUsageAnalysisReportReq.getPartno())).collect(Collectors.toList());
        }
        //刀具类型过滤
        if (StringUtils.isNotBlank(toolTypeUsageAnalysisReportReq.getType())) {
            filterList = filterList.stream().filter(toolInventoryLocationEntity -> toolInventoryLocationEntity.getType().contains(toolTypeUsageAnalysisReportReq.getType())).collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(filterList)) {
            pageList = CommonUtil.pageList(filterList, toolTypeUsageAnalysisReportReq.getPageNo(), toolTypeUsageAnalysisReportReq.getPageSize());
            if (CollectionUtil.isNotEmpty(pageList)) {
                pageList.forEach(toolInventoryLocationEntity -> {
                    toolInventoryLocationEntity.setLocationName(toolLieService.getLocationNameByLocationId(toolInventoryLocationEntity.getInventoryLocationId(), ""));
                });
            }
        }
        return new PageResult<>(pageList, (long) filterList.size());
    }

    public PageResult<ToolTypeUsageAnalysisReportDetailEntity> queryToolTypeUsageAnalysisReportDetail(ToolTypeUsageAnalysisReportDetailReq toolTypeUsageAnalysisReportDetailReq) {
        LambdaQueryWrapper<ToolPartEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportDetailReq.getPartno())) {
            lambdaQueryWrapper.eq(ToolPartEntity::getPartno, toolTypeUsageAnalysisReportDetailReq.getPartno());
        } else if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportDetailReq.getToolNo())) {
            lambdaQueryWrapper.eq(ToolPartEntity::getToolNo, toolTypeUsageAnalysisReportDetailReq.getToolNo());
        }
        if (StringUtils.isNotEmpty(toolTypeUsageAnalysisReportDetailReq.getRfid())) {
            lambdaQueryWrapper.like(ToolPartEntity::getUniqueId, toolTypeUsageAnalysisReportDetailReq.getRfid());
        }
        List<ToolPartEntity> toolPartEntityList = toolPartMapper.selectList(lambdaQueryWrapper);
        List<ToolTypeUsageAnalysisReportDetailEntity> toolTypeUsageAnalysisReportDetailEntityList = new ArrayList<>();
        toolPartEntityList.forEach(toolPartEntity -> {
            LambdaQueryWrapper<ToolPartEntryExitRecordEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ToolPartEntryExitRecordEntity::getToolPartId, toolPartEntity.getId());
            List<ToolPartEntryExitRecordEntity> toolPartEntryExitRecordEntityList = toolPartEntryExitRecordMapper.selectList(lambdaQueryWrapper1);
            List<Integer> list = new ArrayList<>();
            toolPartEntryExitRecordEntityList.forEach(toolPartEntryExitRecordEntity -> {
                list.add(toolPartEntryExitRecordEntity.getEntryExitRecordId());
            });
            LambdaQueryWrapper<EntryExitRecordEntity> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(EntryExitRecordEntity::getWarehouseName, toolTypeUsageAnalysisReportDetailReq.getWarehouseName());
            if (CollectionUtil.isNotEmpty(list)) {
                lambdaQueryWrapper2.in(EntryExitRecordEntity::getId, list);
            } else {
                lambdaQueryWrapper2.eq(EntryExitRecordEntity::getId, -1);
            }

            List<EntryExitRecordEntity> entryExitRecordEntityList = entryExitRecordMapper.selectList(lambdaQueryWrapper2);
//            LambdaQueryWrapper<TypeItemEntity> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper3.eq(TypeItemEntity::getType,toolPartEntity.getToolType());
            String typeName = typeItemMapper.getTypeNameByType(toolPartEntity.getToolType());
            entryExitRecordEntityList.forEach(entryExitRecordEntity -> {
                ToolTypeUsageAnalysisReportDetailEntity toolTypeUsageAnalysisReportDetailEntity = new ToolTypeUsageAnalysisReportDetailEntity();
                LocationNameVo locationNameVo = inventoryLocationRespository.queryLocation(toolPartEntity.getId());
                if (locationNameVo != null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    String locationName = stringBuilder.append(locationNameVo.getTypeName()).append("-")
                            .append(locationNameVo.getWarehouseName()).append("-库位")
                            .append(locationNameVo.getLocationNum()).toString();
                    toolTypeUsageAnalysisReportDetailEntity.setLocation(locationName);
                }
                if (entryExitRecordEntity.getType().equals("inbound")) {
                    toolTypeUsageAnalysisReportDetailEntity.setInboundTime(entryExitRecordEntity.getCreateTime());
                } else if (entryExitRecordEntity.getType().equals("outbound")) {
                    toolTypeUsageAnalysisReportDetailEntity.setOutboundTime(entryExitRecordEntity.getCreateTime());
                }
                toolTypeUsageAnalysisReportDetailEntity.setToolType(typeName);
                if (StringUtils.isNotEmpty(entryExitRecordEntity.getPartno())) {
                    toolTypeUsageAnalysisReportDetailEntity.setPartno(entryExitRecordEntity.getPartno());
                } else if (StringUtils.isNotEmpty(entryExitRecordEntity.getToolNo())) {
                    toolTypeUsageAnalysisReportDetailEntity.setToolNo(entryExitRecordEntity.getToolNo());
                }
                toolTypeUsageAnalysisReportDetailEntity.setRfid(toolPartEntity.getUniqueId());
                toolTypeUsageAnalysisReportDetailEntityList.add(toolTypeUsageAnalysisReportDetailEntity);
            });

        });
        PageInfo<ToolTypeUsageAnalysisReportDetailEntity> result = new PageInfo<>(CommonUtil.pageList(toolTypeUsageAnalysisReportDetailEntityList, toolTypeUsageAnalysisReportDetailReq.getPageNo(), toolTypeUsageAnalysisReportDetailReq.getPageSize()));
        return new PageResult<>(result.getList(), (long) toolTypeUsageAnalysisReportDetailEntityList.size());

    }

    private Map<String, String> stringToMap(String s) {
        s = s.substring(2, s.length() - 2);
//        s.replaceAll("\"","");
        String[] strs = s.split(",");
        Map<String, String> map = new HashMap<>();
        for (String s1 : strs) {
            String key = s1.split(":")[0];
            key = key.substring(1, key.length() - 1);
            String value = "";
            try {
                value = s1.split(":")[1].replaceAll("\"", "");
            } catch (Exception e) {
            }
            map.put(key, value);
        }
        return map;
    }

    public Object queryToolStock(ToolTypeUsageAnalysisReportReq toolTypeUsageAnalysisReportReq) {
        PageHelper.startPage(toolTypeUsageAnalysisReportReq.getPageNo(), toolTypeUsageAnalysisReportReq.getPageSize());
        List<ToolStockVo> toolStockVos = toolPartRespository.queryToolStock(toolTypeUsageAnalysisReportReq);
        PageInfo<ToolStockVo> toolStockVoPageInfo = new PageInfo<>(toolStockVos);
        if (CollectionUtil.isNotEmpty(toolStockVoPageInfo.getList())) {
            toolStockVoPageInfo.getList().forEach(toolStockVo -> {
                toolStockVo.setInboundNumber(entryExitRecordRepository.selectNumber(toolTypeUsageAnalysisReportReq.getStartTime(), toolTypeUsageAnalysisReportReq.getEndTime(), toolStockVo.getWarehouseName(), toolStockVo.getPartno(), toolStockVo.getToolNo(), "inbound"));
                toolStockVo.setOutboundNumber(entryExitRecordRepository.selectNumber(toolTypeUsageAnalysisReportReq.getStartTime(), toolTypeUsageAnalysisReportReq.getEndTime(), toolStockVo.getWarehouseName(), toolStockVo.getPartno(), toolStockVo.getToolNo(), "outbound"));
            });
        }
        return new PageResult<>(toolStockVoPageInfo.getList(), toolStockVoPageInfo.getTotal());
    }

    public Object queryToolInboundAndOutbound(ToolTypeUsageAnalysisReportReq toolTypeUsageAnalysisReportReq) {
        //PageHelper.startPage(toolTypeUsageAnalysisReportReq.getPageNo() , toolTypeUsageAnalysisReportReq.getPageSize());
        List<InOrOutboundSumVo> resultList = entryExitRecordRepository.selectSumVo(toolTypeUsageAnalysisReportReq);
        List<InOrOutboundSumVo> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(resultList)) {
            pageList = CommonUtil.pageList(resultList, toolTypeUsageAnalysisReportReq.getPageNo(), toolTypeUsageAnalysisReportReq.getPageSize());
        }
        if (CollectionUtil.isNotEmpty(pageList)) {
            pageList.forEach(inOrOutboundSumVo -> {
                if (StringUtils.isNotBlank(inOrOutboundSumVo.getPartno())) {
                    inOrOutboundSumVo.setIdnr(toolForkInfoRespository.selectPartTypeByPartno(inOrOutboundSumVo.getPartno()));
                }
            });
        }
        return new PageResult<>(pageList, (long) resultList.size());
    }

    public Object queryToolInboundAndOutboundDetail(ToolTypeUsageAnalysisReportReq toolTypeUsageAnalysisReportReq) {
        PageHelper.startPage(toolTypeUsageAnalysisReportReq.getPageNo(), toolTypeUsageAnalysisReportReq.getPageSize());
        List<InOrOutboundRecordVo> resultList = entryExitRecordRepository.queryToolInboundAndOutboundDetail(toolTypeUsageAnalysisReportReq);
        PageInfo<InOrOutboundRecordVo> pageInfo = new PageInfo<>(resultList);
        if (CollectionUtil.isNotEmpty(pageInfo.getList())) {
            List<String> collect = pageInfo.getList().stream().filter(inOrOutboundRecordVo -> StringUtils.isNotBlank(inOrOutboundRecordVo.getPartno())).map(InOrOutboundRecordVo::getPartno).collect(Collectors.toList());
            List<ToolForkInfoEntity> toolForkInfoEntities = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(collect)){
                toolForkInfoEntities = toolForkInfoRespository.selectIdByPartnos(collect);
            }
            Map<String, String> partnoIdnrMap = toolForkInfoEntities.stream().collect(Collectors.toMap(ToolForkInfoEntity::getPartno, ToolForkInfoEntity::getIdnr));
            pageInfo.getList().forEach(inOrOutboundRecordVo -> {
                if (StringUtils.isNotBlank(inOrOutboundRecordVo.getPartno())) {
                    inOrOutboundRecordVo.setIdnr(partnoIdnrMap.get(inOrOutboundRecordVo.getPartno()));
                }
                Integer toolPartId = entryExitRecordRepository.selectToolPartIdByEntryId(inOrOutboundRecordVo.getId());
                if(ObjectUtil.isNotNull(toolPartId)){
                    inOrOutboundRecordVo.setNearlyWarehouseName(entryExitRecordRepository.selectNearlyWarehouseName(toolPartId));
                }
            });
        }
        //增加归还前位置字段
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }
}
